<template>
  <div class="model-box">
    <ModuleTitle
    :title=title
    class="t"
    ></ModuleTitle>
    <!--边框-->
    <div class="line-box">
      <i class="l-line"></i>
      <i class="t-line"></i>
    </div>
    <div class="line-box">
      <i class="t_r_line"></i>
      <i class="r_t_line"></i>
    </div>
    <div class="line-box">
      <i class="l_b_line"></i>
      <i class="b_l_line"></i>
    </div>
    <div class="line-box">
      <i class="r_b_line"></i>
      <i class="b_r_line"></i>
    </div>
    <div
    id="container"
    ></div>
    <!--功能-->
    <div class="manage-box">
      <el-tooltip
          class="box-item"
          effect="dark"
          content="图层管理"
          placement="right"
      >
        <div
            class="manage_item"
            @click="showLayer"
        >
          <el-icon><Operation /></el-icon>
        </div>
      </el-tooltip>
      <el-tooltip
          class="box-item"
          effect="dark"
          content="查询"
          placement="right"
      >
        <div
            class="manage_item"
            @click="showQuery"
        >
          <el-icon><Search /></el-icon>
        </div>
      </el-tooltip>
      <el-tooltip
          class="box-item"
          effect="dark"
          content="统计"
          placement="right"
      >
        <div
            class="manage_item"
            @click="showTongji"
        >
          <el-icon><Histogram /></el-icon>
        </div>
      </el-tooltip>
      <el-tooltip
          class="box-item"
          effect="dark"
          content="桩号定位"
          placement="right"
      >
        <div
            class="manage_item"
            @click="showLocation"
        >
          <el-icon><Position /></el-icon>
        </div>
      </el-tooltip>
    </div>


    <!--图层-->
    <div
      class="layer-box"
      v-if="isLayerShow"
    >
      <div class="layer-top">
        <span>图层</span>
        <Close
          style="width: 2vh; height: 2vh;cursor: pointer"
          @click="closeLayer"
        />
      </div>
      <div class="layer-bottom">
        <!--<div class="layer-item">-->
        <!--  <el-checkbox-->
        <!--      v-model="layer.layer14"-->
        <!--      size="small"-->
        <!--      @change="toggleDiTu"-->
        <!--  />-->
        <!--  <span-->
        <!--      style="cursor: pointer"-->
        <!--  >地球模型</span>-->
        <!--</div>-->
        <div class="layer-item">
          <el-checkbox
            v-model="layer.layer6"
            size="small"
            @change="toggleQingxie2"
          />
          <!--<span-->
          <!--  @click="flyToQingxie2"-->
          <!--  style="cursor: pointer"-->
          <!--&gt;倾斜模型</span>-->
          <span
            @click="flyToQingxie2"
            style="cursor: pointer"
          >吉林乙烯厂</span>
        </div>
        <div class="layer-item">
          <el-checkbox
              v-model="layer.layer13"
              size="small"
              @change="toggleZS"
          />
          <span
              @click="flyToZS"
              style="cursor: pointer"
          >正射影像</span>
        </div>
        <div class="layer-item">
          <el-checkbox
            v-model="layer.layer7"
            size="small"
            @change="togglePointCloud"
          />
          <span
              @click="flyToPointCloud"
              style="cursor: pointer"
          >主路点云</span>
        </div>
        <div class="layer-item">
          <el-checkbox
            v-model="layer.layer2"
            size="small"
            @change="togglePointCloud2"
          />
          <span
            @click="flyToPointCloud2"
            style="cursor: pointer"
          >辅路点云</span>
        </div>
        <div class="layer-item">
          <el-checkbox
              v-model="layer.layer12"
              size="small"
              @change="toggleSuiDao"
          />
          <span
              @click="flyToSuiDao"
              style="cursor: pointer"
          >隧道点云</span>
        </div>
        <div class="layer-item">
          <el-checkbox
            v-model="layer.layer3"
            size="small"
            @change="togglePoles"
          />
          <span
            @click="flyToPoles"
            style="cursor: pointer"
          >桩号</span>
        </div>
        <div class="layer-item">
          <el-checkbox
              v-model="layer.layer11"
              size="small"
              @change="togglePoint"
          />
          <span
              @click="flyToPoint"
              style="cursor: pointer"
          >
            点要素
          </span>
        </div>
        <div class="layer-item">
          <el-checkbox
            v-model="layer.layer9"
            size="small"
            @change="toggleLine"
          />
          <span
              @click="flyToLine"
              style="cursor: pointer"
          >
            线要素
          </span>
        </div>
        <div class="layer-item">
          <el-checkbox
            v-model="layer.layer10"
            size="small"
            @change="togglePolygon"
          />
          <span
            @click="flyToPolygon"
            style="cursor: pointer"
          >
            面要素
          </span>
        </div>
      </div>
    </div>

    <!--查询功能区-->
    <div
      class="query-box"
      v-if="isQueryShow"
    >
      <div class="query-top">
        <span>桩号查询</span>
        <Close
          style="width: 2vh; height: 2vh;cursor: pointer"
          @click="closeQuery"
        />
      </div>

        <div class="query-bottom">
          <div class="query-item">
            <!--<div-->
            <!--  :class="{query:value === 1,isKeyActive:keySquare === 1,}"-->
            <!--  @click="startDraw"-->
            <!--&gt;-->
            <!--</div>-->

            <!--桩号查询-->
            <!--<div-->
            <!--  :class="{query:value === 1,isKeyActive:keyPole === 1,}"-->
            <!--  @click="showPole"-->
            <!--&gt;-->
            <!--  桩号查询-->
            <!--</div>-->
            <!--关键字查询-->
            <!--<div-->
            <!--  :class="{query:value === 1,isKeyActive:keyValue === 1,}"-->
            <!--  @click="showKey"-->
            <!--&gt;-->
            <!--  关键字查询-->
            <!--</div>-->
          </div>

          <!--关键字查询表单区-->
          <div class="key" v-if="isKeyShow">
            <el-select
              v-model="keyField"
              class="m-2"
              placeholder="请选择查询字段"
            >
              <el-option
                  v-for="item in keyFieldOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
            <el-input
              v-model="keyWord"
              placeholder="请输入查询关键字"
              clearable
              style="width:35%;margin-left: 8% ;"
              @keyup.enter="startKeyWords()"
            />
            <div class="btn">
              <el-button
                  :icon="Search"
                  circle
                  style="margin-left: 0.8vw;"
                  @click="startKeyWords"
              />
              <el-button
                  type="danger"
                  :icon="Close"
                  circle
                  @click="closeKey"
              />
            </div>
          </div>

          <!--关键字查询结果展示区-->
          <el-scrollbar>
            <div
              class="query-content"
              v-if="isContentShow"
            >
              <el-card
                shadow="always"
              >
                <template #header>
                  <div
                    style="text-align: center;font-size: 1.8vh;letter-spacing: 4px;font-weight: 600;color: #646464;height: 1vh;line-height: 1vh;">
                    <span >属性列表</span>
                  </div>
                </template>
                <el-row>
                  <el-col :span="24">
                    <div
                      class="info-res"
                      v-for="(item,index) in tableData"
                      :key="index"
                    >
                      <div class="res-index">
                        第{{index+1}}条
                      </div>
                      <div class="res-item">
                        <div class="table-info">
                          <div
                              class="table-title"
                          >
                            id
                            <!-- {{ sub.label }} -->
                          </div>
                          <div
                              class="table-content"
                          >
                            {{ item.id }}
                            <!-- {{ sub.label }} -->
                          </div>
                        </div>
                        <div class="table-info">
                          <div
                              class="table-title"
                          >
                            名称
                            <!-- {{ sub.label }} -->
                          </div>
                          <div
                              class="table-content"
                          >
                            {{ item.name }}
                            <!-- {{ sub.label }} -->
                          </div>
                        </div>
                        <div class="table-info">
                          <div
                              class="table-title"
                          >
                            类别
                            <!-- {{ sub.label }} -->
                          </div>
                          <div
                              class="table-content"
                          >
                            {{ resArr.type }}
                            <!-- {{ sub.label }} -->
                          </div>
                        </div>
                        <div class="table-info">
                          <div
                              class="table-title"
                          >
                            定位
                            <!-- {{ sub.label }} -->
                          </div>
                          <div
                              class="table-content"
                          >
                            <el-button
                              type="success"
                              :icon="Location"
                              @click="flyToRes(item.position)"
                            />
                            <!-- {{ sub.label }} -->
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-scrollbar>

          <!--桩号查询表单区-->
          <div class="pole">
            <div class="form">
              <div class="form-1">
              <el-select
                v-model="pole1"
                class="m-2"
                placeholder="选择起始桩号"
              >
                <el-option
                    v-for="item in poleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              <el-select
                  v-model="pole2"
                  class="m-2"
                  placeholder="选择结束桩号"
              >
                <el-option
                    v-for="item in poleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              </div>
              <div class="form-2">
                <el-select
                    v-model="poleKey"
                    class="m-2"
                    placeholder="选择类别"
                >
                  <el-option
                      v-for="item in poleKeyOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
                <div class="btn">
                  <el-button
                      :icon="Search"
                      circle
                      style="margin-left: 0.8vw;"
                      @click="startPole"
                  />
                  <el-button
                      type="danger"
                      :icon="Close"
                      circle
                      @click="closePole"
                  />
                </div>
              </div>
            </div>
          </div>

          <!--桩号查询结果展示区-->
          <el-scrollbar>
            <div
                class="pole-content"
                v-show="isPoleContentShow"
            >
              <el-table :data="poleData" style="width: 100%">
                <el-table-column prop="id" label="id" width="120" />
                <el-table-column prop="zh" label="桩号" width="120" />
                <el-table-column prop="type" label="类型" width="120" />
                <el-table-column label="定位">
                  <template #default="scope">
                    <div>
                      <el-button
                          type="success"
                          :icon="Location"
                          @click="flyToRes(scope.row.position,scope.row.entityType)"
                      />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-scrollbar>

        </div>
    </div>

    <!--桩号定位-->
    <div class="poles-location" v-if="isLocationShow">
      <div class="top">
        <span>桩号定位</span>
        <el-icon 
          @click="closeLocation"
        >
          <Close />
        </el-icon>
      </div>
      <div class="bot">
        <el-input
          v-model="poleNumber"
          placeholder="输入桩号"
          clearable
          type="number"
          min="1"
          max="132"
        />
        <el-button
          type="success"
          :icon="LocationInformation"
          circle
          @click="toCurrentPole"
        />
      </div>
    </div>

    <!--桩号间统计-->
    <div class="tongji" v-if="isTongjiShow">
      <div class="tongji-top">
        <span>桩间统计</span>
        <el-icon
            @click="closeTongji"
            style="cursor: pointer"
        >
          <Close />
        </el-icon>
      </div>
      <div class="tongji-bot">
        <!--桩号查询表单区-->
        <div class="tongji-pole">
          <div class="tongji-form">
            <div class="tongji-form-1">
              <el-select
                  v-model="totalPole1"
                  class="m-3"
                  placeholder="选择起始桩号"
              >
                <el-option
                    v-for="item in poleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              <el-select
                  v-model="totalPole2"
                  class="m-3"
                  placeholder="选择结束桩号"
              >
                <el-option
                    v-for="item in poleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              <el-select
                  v-model="totalKey"
                  class="m-3"
                  placeholder="选择类别"
              >
                <el-option
                    v-for="item in tongjiOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              <div class="tongji-btn">
                <el-button
                    :icon="Search"
                    circle
                    style="margin-left: 0.8vw;"
                    @click="startTongji"
                />
              </div>
            </div>
          </div>
        </div>

        <!--装件查询结果展示区-->
        <el-scrollbar>
          <div class="tongji-res" v-if="isTongJiResShow">
            <div
                id="main"
                style="height: 32vh;width: 37vw;margin-bottom: 1vh;z-index: 999;padding-left: 1vw"
            >
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script setup>
import ModuleTitle from "@/components/Public/ModuleTitle.vue";
import '@/assets/css/base.less'
import {onMounted, reactive, ref} from "vue";
import axios from "axios";
import {Close, Search, Location, Operation, Histogram, Position, LocationInformation} from "@element-plus/icons-vue";
import {ElScrollbar, ElInput, ElButton, ElMessage, ElCard, ElRow, ElCol, ElCheckbox, ElOption, ElSelect, ElIcon, ElTooltip, ElTable, ElTableColumn} from "element-plus";
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
// 引入柱状图图表，图表后缀都为 Chart
import { PieChart  } from 'echarts/charts';
// 引入提示框，标题，直角坐标系，数据集，内置数据转换器组件，组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent
} from 'echarts/components';
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';
// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  PieChart ,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  LegendComponent
]);

const title = ref('地图影像')

// 查询框显隐
const isQueryShow = ref(false)
// 图层框显隐
const isLayerShow = ref(false)
const value = 1
// 图层功能激活
let layerValue = ref(0)
// 查询功能激活
let queryValue = ref(0)
// 关键字查询激活
let keyValue = ref(0)
// 桩号查询激活
let keyPole = ref(0)
// 框选查询激活
const keySquare = ref(0)
// 关键字查询字段选择
const keyField = ref('')
// 关键字查询输入
const keyWord = ref('210422')
// 关键字查询显隐
const isKeyShow = ref(false)
// 桩号查询显隐
const isPoleShow = ref(false)
// 信息展示表格显隐
const isContentShow = ref(false)
//表格数据-key
const tableData = ref([])
// 返回数据
let resArr = ref([])
//图层管理
const layer = reactive({
  layer2 : false, //
  layer3 : false, //
  layer6 : false, //
  layer7 : false, //
  layer9 : false, //
  layer10 : false, //
  layer11 : false, //
  layer12 : false, //
  layer13 : false, //
  layer14 : false,
})
// 关键字选择options
const keyFieldOptions = [
  {
    label:'村县',
    value: 'C_XIAN',
  },{
    label:'字段2',
    value: 'Option2',
  },{
    label:'字段3',
    value: 'Option3',
  },{
    label:'字段4',
    value: 'Option4',
  },{
    label:'字段5',
    value: 'Option5',
  },
]
//桩号查询：桩1
const pole1 = ref()
//桩号查询：桩2
const pole2 = ref()
// 桩号查询，类别
const poleKey = ref()
// 桩号列表option
const poleOptions = ref([])
// 桩号类别option
const poleKeyOptions = ref([
  {
    value:'1001',
    label:'交通点'
  },{
    value:'1002',
    label:'信号灯'
  },{
    value:'1003',
    label:'设施点'
  },{
    value:'3805011',
    label:'门墩'
  },{
    value:'3805011',
    label:'路灯'
  },{
    value:'3805021',
    label:'杆式照射灯'
  },{
    value:'3805041',
    label:'单柱广告牌'
  },{
    value:'4510021',
    label:'路标'
  },{
    value:'5103031',
    label:'电线塔'
  },{
    value:'5104011',
    label:'变电站'
  },{
    value:'5401001',
    label:'不明井'
  },{
    value:'5430071',
    label:'消防栓'
  },{
    value:'5103031',
    label:'电线塔'
  },{
    value:'2001',
    label:'交通线'
  },{
    value:'2002',
    label:'设施线'
  },{
    value:'2101012',
    label:'河流岸线'
  },{
    value:'2203012',
    label:'支渠线'
  },{
    value:'2209002',
    label:'涵洞'
  },{
    value:'2210002',
    label:'单线干沟'
  },{
    value:'2301022',
    label:'池塘坎'
  },{
    value:'2709002',
    label:'栅栏坎'
  },{
    value:'3802014',
    label:'围墙'
  },{
    value:'3802022',
    label:'栅栏'
  },{
    value:'3802032',
    label:'篱笆'
  },{
    value:'3802042',
    label:'活树篱笆'
  },{
    value:'3802052',
    label:'铁丝网'
  },{
    value:'3804092',
    label:'檐廊'
  },{
    value:'3805042',
    label:'广告牌'
  },{
    value:'5104022',
    label:'电杆上的变压器'
  },{
    value:'5441022',
    label:'雨水箅子（依比例尺）'
  },{
    value:'7506052',
    label:'未加固坎'
  },{
    value:'7506062',
    label:'已加固坎'
  },{
    value:'2209003',
    label:'涵洞'
  },{
    value:'2301023',
    label:'池塘'
  },{
    value:'2610003',
    label:'贮水池'
  },{
    value:'3001',
    label:'房屋面'
  },{
    value:'3002',
    label:'设施面'
  },{
    value:'3004',
    label:'电缆箱'
  },{
    value:'3804023',
    label:'门顶'
  },{
    value:'3804073',
    label:'门墩'
  },{
    value:'3804083',
    label:'支柱'
  },{
    value:'3805033',
    label:'岗亭'
  },{
    value:'4103073',
    label:'站台'
  },{
    value:'4103074',
    label:'站台雨棚'
  },{
    value:'4501053',
    label:'停车场'
  },{
    value:'4503013',
    label:'单层桥'
  },{
    value:'4504003',
    label:'桥墩'
  },{
    value:'4505043',
    label:'人行拱桥'
  },{
    value:'5103033',
    label:'电线塔面'
  },{
    value:'5104014',
    label:'露天变电站'
  },{
    value:'5441024',
    label:'雨水箅子'
  },{
    value:'7601013',
    label:'未加固斜坡面'
  },{
    value:'7601023',
    label:'已加固斜面'
  },{
    value:'8104013',
    label:'果园'
  },{
    value:'8105013',
    label:'成林'
  },{
    value:'8105023',
    label:'幼林'
  },{
    value:'8105033',
    label:'灌木林'
  },{
    value:'8105073',
    label:'苗圃'
  },
])
// 是否第一次飞行
let firstFly = ref()
// 桩号查询结构表格区展示
let isPoleContentShow = ref(false)
// 桩号查询结构表格区数据
const poleData = ref([])
// echarts显隐
let isEchartsShow = ref(false)
// echarts options
let myChart
let option
// 桩号定位
let isLocationShow = ref(false)
// 定位目标桩号
let poleNumber = ref()
//桩间统计表单
const totalPole1 = ref()
const totalPole2 = ref()
const totalKey = ref()
// 统计面板展示
const isTongjiShow = ref(false)
// 统计结果展示
const isTongJiResShow = ref(false)
// 统计类别选择
const tongjiOption = [
  {
    value:1,
    label:'点'
  },{
    value:2,
    label:'线'
  },{
    value:3,
    label:'面'
  },
]

onMounted(()=>{
  // handleAsstoken()
  Cesium.Ion.defaultAccessToken ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZmU4ODg5MS1mYTYxLTQ1MTMtOTM1My03YzhhMTM3ZWUxNDAiLCJpZCI6MTIyNTgyLCJpYXQiOjE2NzQ5NjQ0ODR9.e9Q99Z21wt6NjtUEtGHIjYoNq8WGHsisnoysbVptffE";
  //在线地形
  // window.terrainProvider = new Cesium.createWorldTerrain()
  // const scene = new Cesium.Scene()
  // window.scene  = new Cesium.Scene()
  initCesium()
  // getpoint()
  let iframe = document.getElementsByClassName('cesium-infoBox-iframe')[0];
  iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts allow-popups allow-forms');
  iframe.setAttribute('src', ''); //必须设置src为空 否则不会生效。
  // 给桩号下拉框赋值
  for(let i = 0; i <= 131; i++){
    poleOptions.value.push({
      label: `${i}号桩`,
      value: i,
    })
  }
})

const initCesium = ()=>{
  if (isOnline()) {
    // 执行需要网络连接的操作
    window.viewer = new Cesium.Viewer('container',{
      animation:false,//动画小部件
      baseLayerPicker:false,//地图图层组件
      fullscreenButton:false,//全屏组件
      geocoder:false,//地理编码搜索组件
      homeButton:false,//首页组件
      // infoBox:false,//信息框
      sceneModePicker:false,//场景模式
      selectionIndicator:false,//选取指示器组件
      timeline:false,//时间轴
      navigationHelpButton:false,//帮助按钮
      navigationInstructionsInitiallyVisible:false,
      terrainProvider:window.terrainProvider,
      sceneMode: Cesium.SceneMode.SCENE3D
    })

    // window.viewer.scene.globe.show = false
  } else {
    // 处理网络未连接的情况
    console.error('Network is not connected.');
    // 可以向用户显示友好的提示信息，例如使用alert()或者将错误信息渲染到页面上的特定区域
    // alert('Network is not connected. Please check your connection.');
  }
}

// 显示查询
const showQuery = ()=>{
  isQueryShow.value = true
  queryValue.value = 1
  showPole()
}

// 显示图层
const showLayer = ()=>{
  isLayerShow.value = true
  layerValue.value = 1
}

const isOnline = () => {
  return navigator.onLine
}

//底图
const toggleDiTu = () => {
  if(layer.layer14){
    // 加载模型
    window.viewer.scene.globe.show = true
  } else {
    // 移除模型
    window.viewer.scene.globe.show = false
    viewer.scene.skyAtmosphere.showSkyAtmosphere = false;
  }
}
// 倾斜图层2切换
const toggleQingxie2 = ()=>{
  if(layer.layer6){
    // 加载模型
    loadQingxie2()
  } else {
    // 移除模型
    window.viewer.scene.primitives.remove(window.qingxie2)
  }
}

// 加载倾斜模型2
const loadQingxie2 = ()=>{
  const qingxie2 = new Cesium.Cesium3DTileset({
    url: 'http://120.46.72.236:9003/model/Q1QkWoPk/tileset.json',
    // url: 'http://localhost:9003/model/vwuY1184/tileset.json',
  })
  window.qingxie2 = qingxie2
  window.viewer.scene.primitives.add(qingxie2)
}

const toggleZS = ()=>{
  if(layer.layer13){
    // 加载模型
    loadZS()
  } else {
    // 移除模型
    window.viewer.imageryLayers.remove(window.zs)
  }
}

// 加载倾斜模型
const loadZS = ()=>{
  const zs = new Cesium.UrlTemplateImageryProvider({
    "url": "http://localhost:9003/image/wmts/tLhp0xzK/{z}/{x}/{y}"
  })
  const r = window.viewer.imageryLayers.addImageryProvider(zs);
  window.zs = r
}

// 定位到倾斜模型
const flyToZS = ()=>{
  window.viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(123.66890, 41.79341, 5000)
  });
}

// 定位到倾斜模型2
const flyToQingxie2 = ()=>{
  window.viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(126.63692, 43.86562, 5000)
  });
}

// 点云层切换
const togglePointCloud = ()=>{
  if(layer.layer7){
    // 加载模型
    loadPointCloud()
  } else {
    // 移除模型
    window.viewer.scene.primitives.remove(window.pointCloud)
    window.viewer.terrainProvider = window.terrainProvider
    window.viewer.scene.globe.depthTestAgainstTerrain = true;//是否检查深度
  }
}
// 加载点云
const loadPointCloud = ()=>{
  //创建点云
  let pointCloud = new Cesium.Cesium3DTileset({
    url: 'http://localhost:9003/model/vTKsFBwz/tileset.json',
  })
  //添加到图层
  window.viewer.scene.primitives.add(pointCloud);
  pointCloud.style = new Cesium.Cesium3DTileStyle({
    pointSize: 3,
  })
  window.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
  window.viewer.scene.globe.depthTestAgainstTerrain = false;//是否检查深度
  window.viewer.scene.primitives.add(pointCloud)
  window.pointCloud = pointCloud
}

// 定位到点云
const flyToPointCloud = ()=>{
  window.viewer.flyTo(window.pointCloud)
}


// 点云层2切换
const togglePointCloud2 = ()=>{
  if(layer.layer2){
    // 加载模型
    loadPointCloud2()
  } else {
    // 移除模型
    window.viewer.scene.primitives.remove(window.pointCloud2)
    window.viewer.terrainProvider = window.terrainProvider
    window.viewer.scene.globe.depthTestAgainstTerrain = true;//是否检查深度
  }
}
// 加载点云2
const loadPointCloud2 = ()=>{
  //创建点云
  let pointCloud2 = new Cesium.Cesium3DTileset({
    url: 'http://localhost:9003/model/6GK8xWiD/tileset.json',
    // maximumMemoryUsage: 1024,
  })
  //添加到图层
  window.viewer.scene.primitives.add(pointCloud2);
  pointCloud2.style = new Cesium.Cesium3DTileStyle({
    pointSize: 3,
  })
  // window.viewer.terrainProvider = undefined;
  window.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
  window.viewer.scene.globe.depthTestAgainstTerrain = false;//是否检查深度
  window.viewer.scene.primitives.add(pointCloud2)
  window.pointCloud2 = pointCloud2
}

// 定位到点云2
const flyToPointCloud2 = ()=>{
  window.viewer.flyTo(window.pointCloud2)
}

// 隧道切换
const toggleSuiDao = ()=>{
  if(layer.layer12){
    // 加载模型
    loadSuiDao()
  } else {
    // 移除模型
    window.viewer.scene.primitives.remove(window.loadSuiDao)
    window.viewer.terrainProvider = window.terrainProvider
    window.viewer.scene.globe.depthTestAgainstTerrain = true;//是否检查深度
  }
}
// 加载隧道
const loadSuiDao = ()=>{
  //创建点云
  let loadSuiDao = new Cesium.Cesium3DTileset({
    url: 'http://localhost:9003/model/hg2lpgQ6/tileset.json',
    // maximumMemoryUsage: 1024,
  })
  //添加到图层
  window.viewer.scene.primitives.add(loadSuiDao);
  loadSuiDao.style = new Cesium.Cesium3DTileStyle({
    pointSize: 3,
  })
  // window.viewer.terrainProvider = undefined;
  window.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
  window.viewer.scene.globe.depthTestAgainstTerrain = false;//是否检查深度
  window.viewer.scene.primitives.add(loadSuiDao)
  window.loadSuiDao = loadSuiDao
}

// 定位到隧道
const flyToSuiDao = ()=>{
  window.viewer.flyTo(window.loadSuiDao)
}

// 桩号图层切换
const togglePoles = ()=>{
  if(layer.layer3){
    // 加载桩号
    loadPoles()
  } else {
    // 移除模型
    window.viewer.imageryLayers.remove(window.wmsLayer)
  }
}
// 加载桩号
const loadPoles = ()=>{
  //创建点云
  let poles = new Cesium.WebMapServiceImageryProvider({
    url: "http://www.hydlxx.com:8080/geoserver/hywebgis/wms",
    layers: "hywebgis:sihuanZhuanghao4490",
    parameters: {
      service: "WMS",
      format: "image/png",
      transparent: true,
      // opacity : 1,
    },
  });
  //viewer.imageryLayers.addImageryProvider(wmsImageryProvider)
  const wmsLayer = window.viewer.imageryLayers.addImageryProvider(poles);
  window.wmsLayer = wmsLayer
  window.viewer.imageryLayers.raiseToTop(wmsLayer)
}

// 定位到桩号
const flyToPoles = ()=>{
  window.viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(123.605665, 41.958818, 500)
  })
}

// 点图层切换
const togglePoint = ()=>{
  if(layer.layer11){
    // 加载点
    loadPoint()
  } else {
    // 移除模型
    window.viewer.imageryLayers.remove(window.point)
  }
}
// 加载点
const loadPoint = ()=>{
  //创建点云
  let point = new Cesium.WebMapServiceImageryProvider({
    url: "http://www.hydlxx.com:8080/geoserver/hywebgis/wms",
    layers: "hywebgis:sihuanPoint4490",
    parameters: {
      service: "WMS",
      format: "image/png",
      transparent: true,
    },
  })
  const wmsLayer = window.viewer.imageryLayers.addImageryProvider(point)
  window.point = wmsLayer
}

// 定位到点
const flyToPoint = ()=>{
  window.viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(123.605665, 41.958818, 500)
  })
//   longitude: 123.594503, latitude: 41.951897, altitude: 81.44
}

// 线图层切换
const toggleLine = ()=>{
  if(layer.layer9){
    // 加载桩号
    loadLine()
  } else {
    // 移除模型
    window.viewer.imageryLayers.remove(window.line)
  }
}
// 加载线
const loadLine = ()=>{
  //创建点云
  let line = new Cesium.WebMapServiceImageryProvider({
    url: "http://www.hydlxx.com:8080/geoserver/hywebgis/wms",
    layers: "hywebgis:sihuanPoline4490",
    parameters: {
      service: "WMS",
      format: "image/png",
      transparent: true,
      // opacity : 1,
    },
  });
  //viewer.imageryLayers.addImageryProvider(wmsImageryProvider)
  const wmsLayer = window.viewer.imageryLayers.addImageryProvider(line);
  window.line = wmsLayer
}

// 定位到线
const flyToLine = ()=>{
  window.viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(123.605665, 41.958818, 500)
  });
//   longitude: 123.594503, latitude: 41.951897, altitude: 81.44
}

// 面图层切换
const togglePolygon = ()=>{
  if(layer.layer10){
    // 加载桩号
    loadPolygon()
  } else {
    // 移除模型
    window.viewer.imageryLayers.remove(window.polygon)
  }
}
// 加载面
const loadPolygon = ()=>{
  //创建点云
  let polygon = new Cesium.WebMapServiceImageryProvider({
    url: "http://www.hydlxx.com:8080/geoserver/hywebgis/wms",
    layers: "hywebgis:sihuanPolygon4490",
    parameters: {
      service: "WMS",
      format: "image/png",
      transparent: true,
      // opacity : 1,
    },
  });
  //viewer.imageryLayers.addImageryProvider(wmsImageryProvider)
  const wmsLayer = window.viewer.imageryLayers.addImageryProvider(polygon);
  window.polygon = wmsLayer
}

// 定位到面
const flyToPolygon = ()=>{
  window.viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(123.605665, 41.958818, 500)
  });
//   longitude: 123.594503, latitude: 41.951897, altitude: 81.44
}


// 获取鼠标点击坐标
const getpoint = (e)=>{
  const viewer = window.viewer
  let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  handler.setInputAction(function(event){
    let ray = viewer.camera.getPickRay(event.position);
    // console.log(ray,'ray');
    let cartesian = viewer.scene.globe.pick(ray, viewer.scene);
    // console.log(cartesian,'cartesian');
    let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
    let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
    let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
    let alt = cartographic.height; // 高度
    let coordinate = {
      longitude: Number(lng.toFixed(6)),
      latitude: Number(lat.toFixed(6)),
      altitude: Number(alt.toFixed(2))
    }
    console.log(coordinate)
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}


// 关闭查询功能
const closeQuery = ()=>{
  isQueryShow.value = false
  queryValue.value = 0
  closePole()
  closeKey()
}

// 关闭图层功能
const closeLayer = ()=>{
  isLayerShow.value = false
  layerValue.value = 0
  // if(layer.layer2){
  //   window.viewer.terrainProvider = window.terrainProvider
  //   window.viewer.scene.globe.depthTestAgainstTerrain = true;//是否检查深度
  // }
}

// 显示关键字搜索input
const showKey = ()=>{
  isPoleShow.value = false
  isKeyShow.value = true
  keyValue.value = 1
  // 首次跳转视角
  firstFly.value = true
}

// 隐藏关键字搜索
const closeKey = ()=>{
  keyField.value = ''
  isKeyShow.value = false
  keyValue.value = 0
  keyWord.value = ''
  isContentShow.value = false
  resArr.value = []
  firstFly.value = null
  window.viewer.entities.removeAll() //关闭后移除所有实体
}


// 关键字转Unicode
const toUnicode = (key)=>{
  let res = []
  for(let i = 0; i< key.length; i++) {
    res[i] = ("00" + key.charCodeAt(i).toString(16)).slice(-4);
  }
  return "\\u" + res.join("\\u");
}

// 是否包含中文
const  containsChinese = (str)=>{
  // 使用正则表达式判断字符串中是否包含中文字符
  let reg = /[\u4e00-\u9fa5]/;
  return reg.test(str);
}

// 开始关键字查询
const startKeyWords = ()=>{
  if(keyWord.value === '' || keyField.value === ''){
    return ElMessage({
      type:'error',
      message:'请正确输入参数'
    })
  } else {
    // 判断关键字中是否有中文
    let key
    if(containsChinese(keyWord.value)){
      key = toUnicode(keyWord.value)
    }
    // 字段转Unicode
    const ziduan = toUnicode(keyField.value)
    axios.post('http://www.localhost.com:8080/geoserver/hywebgis/wfs',{
      data:`<?xml version="1.0" encoding="UTF-8"?>
<wfs:GetFeature xmlns:wfs="http://www.opengis.net/wfs"
                xmlns:ogc="http://www.opengis.net/ogc"
                xmlns:gml="http://www.opengis.net/gml"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                service="WFS"
                version="1.1.0"
                xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd">
  <wfs:Query typeName="hywebgis:%E4%BF%A1%E5%8F%B7%E7%81%AF4490">
    <wfs:Filter>
      <ogc:PropertyIsEqualTo>
        <ogc:PropertyName>类型</ogc:PropertyName>
        <ogc:Literal>信号灯</ogc:Literal>
      </ogc:PropertyIsEqualTo>
    </wfs:Filter>
  <wfs:outputFormat>application/json</wfs:outputFormat>
  </wfs:Query>
</wfs:GetFeature>`
    },{contentType:"application/json"}).then((res)=>{
      console.log(res)
    })
    // axios.get('http://120.46.72.236:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:xb4490&outputFormat=application/json&cql_filter=%22C_SZZCHZ%22+like+%27%25\u65e5\u843d%25%27').then((res)=>{
    // // axios.get(`http://120.46.72.236:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:xb4490&outputFormat=application/json&cql_filter=%22${ziduan}%22+like+%27%25${key}%25%27`).then((res)=>{
    //   console.log(res.data.features.length)
    //   if(res.data.features && !res.data.features.length){
    //     resArr.value = []
    //     tableData.value = []
    //     return ElMessage({
    //       type:'info',
    //       message:'未查询到数据'
    //     })
    //   } else if(!res.data){
    //     resArr.value = []
    //     tableData.value = []
    //     return ElMessage({
    //       type:'info',
    //       message:'未查询到数据'
    //     })
    //   } else {
    //     resArr.value = res.data.features
    //     isContentShow.value = true
    //     for (let i = 0; i < resArr.value.length; i++){
    //       // 循环添加每条数据
    //       tableData.value.push({
    //         id:resArr.value[i].id,
    //         type:resArr.value[i].type,
    //         name:resArr.value[i].geometry_name,
    //         position:resArr.value[i].geometry.coordinates[0][0][2] ? resArr.value[i].geometry.coordinates[0][0][2] : ''
    //       })
    //     }
    //   }
    // })
  }
}


let timer = null
// 定位至关键字查询结果坐标
const flyToRes = (position,type)=>{
  // 避免重复添加相同id的实体
  if(window.viewer.entities.getById('point1')){
    const entity = window.viewer.entities.getById('point1')
    window.viewer.entities.remove(entity)
  }
  // 若查询到的位置为空，直接返回提示，不进行跳转
  if(!position){
    return ElMessage({
      message:'当前数据没有位置信息',
      type:'warning'
    })
  }
  if(type === 'Point'){
    // 清除定时器
    if (timer) {
      clearTimeout(timer); // 清除之前的定时器
    }
      const listener = window.viewer.entities.add({
        id:'point1',
        point:{
          pixelSize: 20,
          outlineColor: Cesium.Color.YELLOW,
          color: Cesium.Color.RED,
          outlineWidth: 10,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 设置为贴地, // 设置多边形的高度
        },
        position: Cesium.Cartesian3.fromDegrees(position[0], position[1]),
        zIndex:999
      })
      if(listener){
        window.viewer.scene.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(position[0], position[1], 500) // 设置一个视图点
        })
        let timer = setTimeout(()=>{
          const entity = window.viewer.entities.getById('point1')
          window.viewer.entities.remove(entity)
        },10000)
      }
  } else if(type === 'MultiLineString'){
    // 清除定时器
    if (!timer) {
      clearTimeout(timer); // 清除之前的定时器
    }
    const positionArr = []
    for (let i = 0; i < position.length; i++){
      positionArr.push(Cesium.Cartesian3.fromDegrees(position[i][0], position[i][1],10))
    }
    const listener = window.viewer.entities.add({
      id:'point1',
      polyline:{
        positions: positionArr,
        width: 5,
        material: Cesium.Color.RED,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 设置为贴地, // 设置多边形的高度
      },
    })
    if(listener){
      window.viewer.scene.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(position[0][0], position[0][1], 800) // 设置一个视图点
      })
      timer = setTimeout(()=>{
        const entity = window.viewer.entities.getById('point1')
        window.viewer.entities.remove(entity)
      },10000)
    }
  } else if(type === 'MultiPolygon'){
    console.log(position)
    // 清除定时器
    if (!timer) {
      clearTimeout(timer); // 清除之前的定时器
    }
    const positionArr = []
    for (let i = 0; i < position[0].length; i++){
      positionArr.push(Cesium.Cartesian3.fromDegrees(position[0][i][0], position[0][i][1],0))
    }
    const listener = window.viewer.entities.add({
      id:'point1',
      polygon: {
        hierarchy: positionArr,
        material: Cesium.Color.RED.withAlpha(1), // 设置多边形的颜色和透明度
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 设置为贴地, // 设置多边形的高度
        fill:true,
        outline:true,
        outlineColor:Cesium.Color.RED.withAlpha(1),
        outlineWidth:5,
        // zIndex:999
      }
    })
    if(listener){
      window.viewer.scene.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(position[0][0][0], position[0][1][1], 100) // 设置一个视图点
      })
      timer = setTimeout(()=>{
        const entity = window.viewer.entities.getById('point1')
        window.viewer.entities.remove(entity)
      },10000)
    }
  }
}

// 显示桩号查询
const showPole = ()=>{
  isKeyShow.value = false
  isPoleShow.value = true
}

let pole
// 开始桩号搜索
const startPole = ()=>{
  if(pole1.value === null || pole2.value === null){
    return ElMessage({
      message:'请选择两个桩号',
      type:'error'
    })
  } else if(pole1.value === pole2.value){
    return ElMessage({
      message:'不能选择两个相同桩号',
      type:'error'
    })
  } else if(pole1.value > pole2.value){
    return ElMessage({
      message:'结束桩号不能小于起始桩号',
      type:'error'
    })
  }
  let base
  if(!poleKey.value){
    // const baseArr = [`http://120.46.72.236:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoint4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value})`,`http://120.46.72.236:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoline4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value})`,`http://120.46.72.236:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPolygon4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value})`]
    const baseArr = [`http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoint4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value})`,`http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoline4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value})`,`http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPolygon4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value})`]

    for (let j = 0; j <= 2; j++){
      axios.get(baseArr[j]).then(res => {
        console.log(res)
        // 处理响应数据
        // 在这里处理要素数据
        if(res.data.features && res.data.features.length === 0){
          return ElMessage({
            type:'info',
            message:'未查询到数据'
          })
        }else {
          resArr.value = res.data.features
          isPoleContentShow.value = true
          for (let i = 0; i < resArr.value.length; i++){
            if(j === 1){
              // 循环添加每条数据
              poleData.value.push({
                id:resArr.value[i].id.substring(17),
                zh:resArr.value[i].properties['桩号']+1,
                type:resArr.value[i].properties['类型'],
                position:resArr.value[i].geometry.coordinates ? resArr.value[i].geometry.coordinates : '',
                entityType:resArr.value[i].geometry.type
              })
            } else if(j === 2){
              // 循环添加每条数据
              poleData.value.push({
                id:resArr.value[i].id.substring(16),
                zh:resArr.value[i].properties['桩号']+1,
                type:resArr.value[i].properties['类型'],
                position:resArr.value[i].geometry.coordinates ? resArr.value[i].geometry.coordinates : ''
              })
            } else if(j === 0){
              // 循环添加每条数据
              poleData.value.push({
                id:resArr.value[i].id.substring(16),
                zh:resArr.value[i].properties['桩号']+1,
                type:resArr.value[i].properties['类型'],
                position:resArr.value[i].geometry.coordinates ? resArr.value[i].geometry.coordinates : ''
              })
            }
          }
        }
      }).catch(error => {
        console.error('请求出错:', error);
      })
    }
  } else {
    // 找到目标对象
    const foundObject = poleKeyOptions.value.find(obj => obj.value === poleKey.value);
    if(foundObject){
      const index = poleKeyOptions.value.indexOf(foundObject)
      if(index < 13){
        // 点
        base = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoint4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value} AND TYPE = ${poleKey.value})`
        // base = `http://120.46.72.236:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoint4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value} AND TYPE = ${poleKey.value})`
        axios.get(base).then(res => {
          console.log(res)
          // 处理响应数据
          // 在这里处理要素数据
          if(res.data.features && res.data.features.length === 0){
            return ElMessage({
              type:'info',
              message:'未查询到数据'
            })
          }else {
            poleData.value = []
            resArr.value = res.data.features
            isPoleContentShow.value = true
            for (let i = 0; i < resArr.value.length; i++){
              // 循环添加每条数据
              poleData.value.push({
                id:resArr.value[i].id.substring(16),
                zh:resArr.value[i].properties['桩号']+1,
                type:resArr.value[i].properties['类型'],
                position:resArr.value[i].geometry.coordinates ? resArr.value[i].geometry.coordinates : '',
                entityType:resArr.value[i].geometry.type
              })
            }
          }
        })
        .catch(error => {
          console.error('请求出错:', error);
        })
        return
      } else if (index >=13 && index < 32){
        //线
        base = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoline4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value} AND TYPE = ${poleKey.value})`
        // base = `http://120.46.72.236:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoline4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value} AND TYPE = ${poleKey.value})`

        axios.get(base).then(res => {
          console.log(res)
          // 处理响应数据
          if(res.data.features && res.data.features.length === 0){
            return ElMessage({
              type:'info',
              message:'未查询到数据'
            })
          }else {
            console.log(res)
            poleData.value = []
            resArr.value = res.data.features
            isPoleContentShow.value = true
            for (let i = 0; i < resArr.value.length; i++){
              // 循环添加每条数据
              poleData.value.push({
                id:resArr.value[i].id.substring(17),
                zh:resArr.value[i].properties['桩号']+1,
                type:resArr.value[i].properties['类型'],
                position:resArr.value[i].geometry.coordinates[0] ? resArr.value[i].geometry.coordinates[0] : '',
                entityType:resArr.value[i].geometry.type
              })
            }
            console.log(poleData.value[0].position)
          }
        }).catch(error => {
          console.error('请求出错:', error);
        })
        return

      } else {
        //面
        base = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPolygon4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value} AND TYPE = ${poleKey.value})`
        // base = `http://120.46.72.236:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPolygon4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${pole1.value} AND ZH < ${pole2.value} AND TYPE = ${poleKey.value})`

        axios.get(base).then(res => {
          console.log(res)
          // 处理响应数据
          // console.log(res.data)
          // 在这里处理要素数据
          if(res.data.features && res.data.features.length === 0){
            return ElMessage({
              type:'info',
              message:'未查询到数据'
            })
          }else {
            poleData.value = []
            resArr.value = res.data.features
            isPoleContentShow.value = true
            for (let i = 0; i < resArr.value.length; i++){
              // 循环添加每条数据
              poleData.value.push({
                id:resArr.value[i].id.substring(18),
                zh:resArr.value[i].properties['桩号']+1,
                type:resArr.value[i].properties['类型'],
                position:resArr.value[i].geometry.coordinates[0] ? resArr.value[i].geometry.coordinates[0] : '',
                entityType:resArr.value[i].geometry.type
              })
            }
          }
        }).catch(error => {
          console.error('请求出错:', error);
        })
        return
      }
    }
  }
}

// 隐藏桩号查询
const closePole = ()=>{
  isPoleShow.value = false
  pole1.value = null
  pole2.value = null
  isPoleContentShow.value = false
  poleData.value = []
  keyPole.value = 0
  resArr.value = []
  poleKey.value = null
  window.viewer.entities.removeAll()
  // 表格
  // myChart = null
  // option = null
}


/*桩号定位*/
// 显示桩号定位
const showLocation = ()=>{
  isLocationShow.value = true
}
// 关闭桩号定位
const closeLocation = ()=>{
  isLocationShow.value = false
  // 清除实体
  if(window.viewer.entities.getById('zh')){
    const entity = window.viewer.entities.getById('zh')
    window.viewer.entities.remove(entity)
  }
  poleNumber.value = null
}
// 定位至桩号
const toCurrentPole = ()=>{
  let zh
  let timer
  let base = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanZhuanghao4490&outputFormat=application/json&CQL_FILTER=ZH=${poleNumber.value}`

  //查询开始时就清除定时器和实体
  if (timer !== null) {
    clearTimeout(timer); // 清除之前的定时器
  }
  // 清除实体
  if(window.viewer.entities.getById('zh')){
    const entity = window.viewer.entities.getById('zh')
    window.viewer.entities.remove(entity)
  }
  axios.get(base).then(res => {
    const p = res.data.features[0].geometry.coordinates
    if(p){
      // 查询到桩首先定位
      window.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(p[0], p[1], 500)
      });
      // 添加实体
      zh = window.viewer.entities.add({
        id:'zh',
        point:{
          pixelSize: 20,
          outlineColor: Cesium.Color.YELLOW,
          color: Cesium.Color.RED,
          outlineWidth: 10,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        },
        position: Cesium.Cartesian3.fromDegrees(p[0], p[1]),
        zIndex:999
      })
      // 定时器
      if(zh){
        timer = setTimeout(()=>{
          const entity = window.viewer.entities.getById('zh')
          window.viewer.entities.remove(entity)
          timer = null
        },8000)
      }
    } else {
      return ElMessage({
        message:'未查询到该桩号',
        type:'error'
      })
    }

  }).catch((err)=>{
    console.log(err)
  })
}
/*桩间统计*/
// 展示统计面板
const showTongji = ()=>{
  isTongjiShow.value = true
}
// 开始统计
const startTongji = ()=>{
  if(totalPole1.value > totalPole2.value){
    return ElMessage({
      message:'结束桩号不能小于起始桩号',
      type:'error'
    })
  }
  let pointTotal = 0
  let lineTotal = 0
  let polygonTotal = 0
  let z1 = totalPole1.value
  let z2 = totalPole2.value
  let pointBase = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoint4490&outputFormat=application/json&CQL_FILTER=`

  let lineBase = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoline4490&outputFormat=application/json&CQL_FILTER=`

  let polygonBase = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPolygon4490&outputFormat=application/json&CQL_FILTER=`
  isTongJiResShow.value = true
  if (!totalKey.value) {
    axios.get(`${pointBase}(ZH >= ${totalPole1.value} AND ZH < ${totalPole2.value})`)
      .then((res) => {
        pointTotal = res.data.features.length + 1
        return axios.get(`${lineBase}(ZH >= ${totalPole1.value} AND ZH < ${totalPole2.value})`)
      })
      .then((res) => {
        lineTotal = res.data.features.length + 1
        return axios.get(`${polygonBase}(ZH >= ${totalPole1.value} AND ZH < ${totalPole2.value})`)
      })
      .then((res) => {
        polygonTotal = res.data.features.length + 1
        // 初始化echarts
        myChart = echarts.init(document.getElementById('main'))
        // options
        myChart = echarts.init(document.getElementById('main'))
        // options
        option = {
          dataZoom: [
            //滑动条
            {
              xAxisIndex: 0, //这里是从X轴的0刻度开始
              show: true, //是否显示滑动条，不影响使用
              type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
              startValue: 0, // 从头开始。
            },
          ],
          title: {
            text: z1+'号桩与'+z2+'号桩 桩间统计',
            left: 'center',
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: '20%',
          },
          grid:{
            top:30,
          },
          series: [
            {
              type: 'pie',
              radius: '75%',
              left:'20%',
              top:'10%',
              data: [
                { value: pointTotal, name: '点' },
                { value: lineTotal, name: '线' },
                { value: polygonTotal, name: '面' },
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        // setoption
        myChart.setOption(option)
      })
      .catch((error) => {
        console.error(error)
      })
  } else {
    // 使用对象来存储每个类型的计数
    let typeCount = {};
    if(totalKey.value === 1){
      typeCount = {}
      let pointBase = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoint4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${totalPole1.value} AND ZH < ${totalPole2.value} )`
      axios.get(pointBase).then(res=>{
        res.data.features.forEach(item => {
          const type = item.properties.TYPE;
          typeCount[type] = (typeCount[type] || 0) + 1;
        })
        // 初始化echarts
        myChart = echarts.init(document.getElementById('main'))
        // options
        myChart = echarts.init(document.getElementById('main'))
        // options
        option = {
          dataZoom: [
            //滑动条
            {
              xAxisIndex: 0, //这里是从X轴的0刻度开始
              show: true, //是否显示滑动条，不影响使用
              type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
              startValue: 0, // 从头开始。
            },
          ],
          title: {
            text: z1+'号桩与'+z2+'号桩 桩间统计',
            left: 'center',
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: '20%',
          },
          series: [
            {
              type: 'pie',
              radius: '75%',
              left:'40%',
              top:'10%',
              data: [
                { value: typeCount[1001] ? typeCount[1001] : 0, name: '交通点' },
                { value: typeCount[1002] ? typeCount[1002] : 0, name: '信号灯' },
                { value: typeCount[1003] ? typeCount[1003] : 0, name: '设施点' },
                { value: typeCount[3804071] ? typeCount[3804071] : 0, name: '门墩' },
                { value: typeCount[3805011] ? typeCount[3805011] : 0, name: '路灯' },
                { value: typeCount[3805021] ? typeCount[3805021] : 0, name: '杆式照射灯' },
                { value: typeCount[3805041] ? typeCount[3805041] : 0, name: '单柱广告牌' },
                { value: typeCount[4510021] ? typeCount[4510021] : 0, name: '路标' },
                { value: typeCount[5103011] ? typeCount[5103011] : 0, name: '电杆' },
                { value: typeCount[5103031] ? typeCount[5103031] : 0, name: '电线塔' },
                { value: typeCount[5104011] ? typeCount[5104011] : 0, name: '变电站' },
                { value: typeCount[5401001] ? typeCount[5401001] : 0, name: '不明井' },
                { value: typeCount[5430071] ? typeCount[5430071] : 0, name: '消防栓' },
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        // setoption
        myChart.setOption(option)
        console.log(typeCount);
      })
    } else if(totalKey.value === 2){
      typeCount = {}
      let lineBase = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPoline4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${totalPole1.value} AND ZH < ${totalPole2.value} )`
      axios.get(lineBase).then(res=>{
        res.data.features.forEach(item => {
          const type = item.properties.TYPE;
          typeCount[type] = (typeCount[type] || 0) + 1;
        })
        console.log(typeCount)
        // 初始化echarts
        myChart = echarts.init(document.getElementById('main'))
        // options
        myChart = echarts.init(document.getElementById('main'))
        // options
        option = {
          dataZoom: [
            //滑动条
            {
              xAxisIndex: 0, //这里是从X轴的0刻度开始
              show: true, //是否显示滑动条，不影响使用
              type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
              startValue: 0, // 从头开始。
            },
          ],
          title: {
            text: z1+'号桩与'+z2+'号桩 桩间统计',
            left: 'center',
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: '20%',
          },
          series: [
            {
              type: 'pie',
              radius: '75%',
              left:'42%',
              top:'10%',
              data: [
                { value: typeCount[2001] ? typeCount[2001] : 0, name: '交通线' },
                { value: typeCount[2002] ? typeCount[2002] : 0, name: '设施线' },
                { value: typeCount[2002] ? typeCount[2002] : 0, name: '河流岸线' },
                { value: typeCount[2203012] ? typeCount[2203012] : 0, name: '支渠线' },
                { value: typeCount[2209002] ? typeCount[2209002] : 0, name: '涵洞' },
                { value: typeCount[2210002] ? typeCount[2210002] : 0, name: '单线干沟' },
                { value: typeCount[2301022] ? typeCount[2301022] : 0, name: '池塘坎' },
                { value: typeCount[2709002] ? typeCount[2709002] : 0, name: '栅栏坎' },
                { value: typeCount[3802014] ? typeCount[3802014] : 0, name: '围墙' },
                { value: typeCount[3802022] ? typeCount[3802022] : 0, name: '栅栏' },
                { value: typeCount[3802032] ? typeCount[3802032] : 0, name: '篱笆' },
                { value: typeCount[3802042] ? typeCount[3802042] : 0, name: '活树篱笆' },
                { value: typeCount[3802052] ? typeCount[3802052] : 0, name: '铁丝网' },
                { value: typeCount[3804092] ? typeCount[3804092] : 0, name: '檐廊' },
                { value: typeCount[3805042] ? typeCount[3805042] : 0, name: '广告牌' },
                { value: typeCount[5104022] ? typeCount[5104022] : 0, name: '变压器' },
                { value: typeCount[5441022] ? typeCount[5441022] : 0, name: '雨水箅子' },
                { value: typeCount[7506052] ? typeCount[7506052] : 0, name: '未加固坎' },
                { value: typeCount[7506062] ? typeCount[7506062] : 0, name: '已加固坎' },
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        // setoption
        myChart.setOption(option)
        console.log(typeCount);
      })
    } else {
      typeCount = {}
      let polygonBase = `http://10.4.16.219:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typeName=hywebgis:sihuanPolygon4490&outputFormat=application/json&CQL_FILTER=(ZH >= ${totalPole1.value} AND ZH < ${totalPole2.value} )`
      axios.get(polygonBase).then(res=>{
        res.data.features.forEach(item => {
          const type = item.properties.TYPE;
          typeCount[type] = (typeCount[type] || 0) + 1;
        })
        console.log(typeCount)
        // 初始化echarts
        myChart = echarts.init(document.getElementById('main'))
        // options
        myChart = echarts.init(document.getElementById('main'))
        // options
        option = {
          dataZoom: [
            //滑动条
            {
              xAxisIndex: 0, //这里是从X轴的0刻度开始
              show: true, //是否显示滑动条，不影响使用
              type: "slider", // 这个 dataZoom 组件是 slider 型 dataZoom 组件
              startValue: 0, // 从头开始。
            },
          ],
          title: {
            text: z1+'号桩与'+z2+'号桩 桩间统计',
            left: 'center',
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: '20%',
          },
          series: [
            {
              type: 'pie',
              radius: '75%',
              left:'42%',
              top:'10%',
              data: [
                { value: typeCount[2209003] ? typeCount[2209003] : 0, name: '涵洞' },
                { value: typeCount[2301023] ? typeCount[2301023] : 0, name: '池塘' },
                { value: typeCount[2610003] ? typeCount[2610003] : 0, name: '贮水池' },
                { value: typeCount[3001] ? typeCount[3001] : 0, name: '房屋面' },
                { value: typeCount[3002] ? typeCount[3002] : 0, name: '设施面' },
                { value: typeCount[3004] ? typeCount[3004] : 0, name: '电缆箱' },
                { value: typeCount[3804023] ? typeCount[3804023] : 0, name: '门顶' },
                { value: typeCount[3804073] ? typeCount[3804073] : 0, name: '门墩' },
                { value: typeCount[3804083] ? typeCount[3804083] : 0, name: '支柱' },
                { value: typeCount[3805033] ? typeCount[3805033] : 0, name: '岗亭' },
                { value: typeCount[4103073] ? typeCount[4103073] : 0, name: '站台' },
                { value: typeCount[4103074] ? typeCount[4103074] : 0, name: '站台雨棚' },
                { value: typeCount[4501053] ? typeCount[4501053] : 0, name: '停车场' },
                { value: typeCount[4504003] ? typeCount[4504003] : 0, name: '单层桥' },
                { value: typeCount[4504003] ? typeCount[4504003] : 0, name: '桥墩' },
                { value: typeCount[4505043] ? typeCount[4505043] : 0, name: '人行拱桥' },
                { value: typeCount[5103033] ? typeCount[5103033] : 0, name: '电线塔面' },
                { value: typeCount[5104014] ? typeCount[5104014] : 0, name: '露天变电站' },
                { value: typeCount[5441024] ? typeCount[5441024] : 0, name: '雨水箅子' },
                { value: typeCount[7601013] ? typeCount[7601013] : 0, name: '未加固斜坡面' },
                { value: typeCount[7601023] ? typeCount[7601023] : 0, name: '已加固斜面' },
                { value: typeCount[8104013] ? typeCount[8104013] : 0, name: '果园' },
                { value: typeCount[8105013] ? typeCount[8105013] : 0, name: '成林' },
                { value: typeCount[8105023] ? typeCount[8105023] : 0, name: '幼林' },
                { value: typeCount[8105033] ? typeCount[8105033] : 0, name: '灌木林' },
                { value: typeCount[8105073] ? typeCount[8105073] : 0, name: '苗圃' },
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        // setoption
        myChart.setOption(option)
        console.log(typeCount);
      })
    }
  }
}

// 关闭统计
const closeTongji = ()=>{
  isTongjiShow.value = false
  isTongJiResShow.value = false
  totalPole1.value = null
  totalPole2.value = null
  totalKey.value = null
}


</script>

<style scoped lang="less">
.model-box{
  border: 1px solid #034c6a;
  position: absolute;
  top: 11.5%;
  left: 1%;
  width: 98%;
  height: 87%;
  z-index: 99;
  box-shadow: 0px 0px 10px #4788fb;
  .t{
    position: absolute;
    top: 0%;
    left: 63%;
  }
  #container{
    z-index: 999;
    width: 98vw;
    height: 87vh;
  }
  .manage-box{
    position: absolute;
    top: 8%;
    left: 1%;
    color: darkgray;
    display: flex;
    flex-direction: column;
    background-color: rgba(0, 102, 255, 0.3);
    border: 1px solid blue;
    box-shadow: 0 0 17px #33ccff;
    padding: 1vh 0;
    .manage_item{
      text-align: center;
      padding: 1vh;
      font-size: 2.5vh;
      &:hover{
        cursor: pointer;
        color: white;
      }
    }
  }
  .query-box{
    width: 30vw;
    min-height: 15svh;
    max-height:73vh;
    border: 2px solid gray;
    box-shadow: 0 0 5px #E8E8E8;
    position: absolute;
    top: 8%;
    left: 4%;
    color: white;
    background-color: rgba(171,171,171,.3);
    .query-top{
      display: flex;
      justify-content: space-between;
      font-size: 1.8vh;
      padding:10px;
      padding-left: 22px;
      span{
        letter-spacing: 2.5px;
      }
    }
    .query-bottom{
      .query-item{
        display: flex;
        justify-content: space-around;
        margin-top: 2vh;
        .query{
          border: 1px solid white;
          padding: 5px;
          border-radius: 5px;
          color: black;
          background-color: #fff;
          &:hover{
            cursor: pointer;
            background-color: gray;
            color: white;
          }
        }
      }

      //关键字查询表单区
      .key{
        margin: 3vh 0;
        display: flex;
        justify-content: space-around;
      }

      //信息展示区
      .query-content{
        width: 97%;
        max-height: 45vh;
        padding: 1vh 0.5vh;
        .info-res{
          border-bottom: 1px solid rgba(0,0,0,.7);
          margin-bottom: 1.5vh;
          padding-bottom: 0.5vh;
          .res-index{
            font-size: 1.8vh;
            font-weight: 600;
            margin-bottom: 1vh;
          }
          .res-item{
            .table-info{
              display: flex;
              .table-title{
                letter-spacing: 1px;
                text-align: left;
                margin: 1vh 0.2vw;
                font-weight: 500;
                width: 50%;
              }
              .table-content{
                font-size: 1.5vh;
                text-align: center;
                width: 50%;
              }
            }
          }
        }
      }

      //桩号查询表单区
      .pole{
        display: flex;
        margin: 3vh auto;
        .form{
          display: flex;
          flex-direction: column;
          padding-left: 1vw;
          .form-1{
            display: flex;
            justify-content: space-between;
            width: 21vw;
            margin-bottom: 2vh;
          }
          .form-2{
            margin-bottom: 2vh;
            display: flex;
            justify-content: start;
            .btn{
              margin-left: 5vw;
            }
          }
        }
      }
    }
  }

  .layer-box{
    width: 15vw;
    min-height: 30vh;
    max-height:70vh;
    border: 2px solid gray;
    box-shadow: 0 0 5px #E8E8E8;
    position: absolute;
    top: 8%;
    left: 5%;
    color: white;
    background-color: rgba(171,171,171,.3);
    padding-bottom: 2vh;
    .layer-top{
      display: flex;
      justify-content: space-between;
      font-size: 1.8vh;
      padding:10px;
      span{
        letter-spacing: 2.5px;
      }
    }
    .layer-bottom{
      width: 100%;
      padding-left: 2vw;
      .layer-item{
        margin-top: .5vh;
      }
      /deep/.el-checkbox:last-of-type{
        margin-right: .5vw;
      }
    }
  }
}
.isActive{
  color: white;
  border: 1px solid #EEE9E9;
}

/deep/.el-card {
  --el-card-bg-color: rgba(255,255,255,0.8);
}
.isKeyActive{
  background-color: gray;
  color: white;
}
/deep/.el-select .el-input {
  display: flex;
  width: 100%;
  margin-left: 0.5vw;
}

/deep/.el-select {
  width: 8vw;
  margin-right: 0 !important;
}

//信息展示区
.pole-content{
  width: 97%;
  max-height: 43vh;
  padding: 1vh 0.5vh;
  .pole-total{
    padding-bottom: 2vh;
    border-bottom: 1px solid gray;
    margin-bottom: 2vh;
  }
  .pole-res{
    border-bottom: 1px solid rgba(0,0,0,.7);
    margin-bottom: 1.5vh;
    padding-bottom: 0.5vh;
    .pole-index{
      font-size: 1.8vh;
      font-weight: 600;
      margin-bottom: 1vh;
    }
    .pole-item{
      .pole-info{
        display: flex;
        .pole-title{
          letter-spacing: 1px;
          text-align: left;
          margin: 1vh 0.2vw;
          font-weight: 500;
          width: 50%;
        }
        .pole-content{
          font-size: 1.5vh;
          text-align: center;
          width: 50%;
        }
      }
    }
  }
  .echarts-box{
    .e-title{}
  }
}

//桩号定位
.poles-location{
  height: 13vh;
  width: 16vw;
  border: 1px solid blue;
  box-shadow: 0 0 17px #33ccff;
  background-color: rgba(255,255,255,.5);
  position: absolute;
  top: 12%;
  left: 5%;
  .top{
    height: 15%;
    font-size: 1.8vh;
    letter-spacing: 2px;
    display: flex;
    justify-content: space-between;
    padding: 1vh 2vh;
    padding-left: 1vh;
    .el-icon{
      cursor: pointer;
    }
  }
  .bot{
    display: flex;
    justify-content: space-between;
    padding: 0 2vh;
    margin-top: 2vh;
    padding-right: 3vh;
    .el-input{
      width: 10vw;
    }
  }
}

//桩间统计
.tongji{
  top: 8%;
  left: 4%;
  position: absolute;
  max-height: 75vh;
  width: 38vw;
  background-color: rgba(255, 255, 255, 0.5);
  //height: 15vh;
  .tongji-top{
    height: 2.5vh;
    border-bottom: 1px solid darkgray;
    padding: 1vh 1vh 1vh 2vh;
    display: flex;
    justify-content: space-between;
    font-size: 1.8vh;
    letter-spacing: 2px;
    color: white;
  }
  .tongji-bot{
    padding-bottom: 2vh;
    margin-top: 3vh;
    .tongji-form{
      .tongji-form-1{
        display: flex;
        justify-content: space-around;
        .el-select{
          width: 8vw;
        }
        .m-3{}
      }
    }
    .tongji-res{
      max-height: 60vh;
      margin-top: 2vh;
    }
  }
}


#main{
  margin-bottom: 1vh;
  height: 200px;
  width: 530px;
  padding-bottom: 1vh;
  //border-bottom: 1px solid black !important;
}
</style>